/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */
function initLinkManager()
{
    tinyMCEPopup.resizeToInnerSize();

    var inst = tinyMCEPopup.editor;
    var elm = inst.selection.getNode();
    var action = "insert";

    elm = inst.dom.getParent(elm, "A");
    if (elm != null && elm.nodeName == "A") action = "update";

    if(action == 'update')
    {
        setFormValues();
    }

    $('#saveButton').click(function(event){
        event.preventDefault();
        insertAction();
    })
}

function linkLimiter()
{
    if($('#href').val() != '')
    {
        $('#target, #page, #media').attr('disabled', 'disabled');
        if(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g.test($('#href').val()))
        {
            $('#hrefLink').attr('href', $('#href').val()).show();
        }
    }

    if($('#page option:selected').val() != 'null')
    {
        $('#href, #target, #media').attr('disabled', 'disabled');
        val = $('#page option:selected').val().split('_');
        $('#pageLink').attr('href', '/index.php?module=website&action=display&pageId=' + val[0] + '&pageLang=' + val[1]).show();
    }

    if($('#target').html() != null && $('#target option:selected').val() != 'null')
    {
        $('#href, #page, #media').attr('disabled', 'disabled');
    }

    if($('#media').html() != null && $('#media option:selected').val() != 'null')
    {
        $('#href, #target, #page').attr('disabled', 'disabled');
    }

    $('#page').change(function(){
        if($('#page option:selected').val() != 'null')
        {
            $('#target, #href, #media').attr('disabled', 'disabled');
            val = $('#page option:selected').val().split('_');
            $('#pageLink').attr('href', '/index.php?module=website&action=display&pageId=' + val[0] + '&pageLang=' + val[1]).show();
        }
        else
        {
            $('#target, #href, #media').removeAttr('disabled');
            $('#pageLink').hide();
        }
    });

    $('#target').change(function(){
        if($('#target option:selected').val() != 'null')
        {
            $('#page, #href, #media').attr('disabled', 'disabled');
            val = $('#target option:selected').val().split('_');
            id = $('#target option:selected').attr('title');
            $('#targetLink').attr('href', '/index.php?module=website&action=display&pageId=' + id + '&pageLang=' + val[1]).show();
        }
        else
        {
            $('#page, #href, #media').removeAttr('disabled');
            $('#targetLink').hide();
        }
    });

    $('#media').change(function(){
        if($('#media option:selected').val() != 'null')
        {
            $('#page, #href, #target').attr('disabled', 'disabled');
        }
        else
        {
            $('#page, #href, #target').removeAttr('disabled');
        }
    });

    $('#href').keyup(function(){
        if($('#href').val() != '')
        {
            $('#target, #page, #media').attr('disabled', 'disabled');
            if(/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/g.test($('#href').val()))
            {
                $('#hrefLink').attr('href', $('#href').val()).show();
            }
        }
        else
        {
            $('#target, #page, #media').removeAttr('disabled');
            $('#hrefLink').attr('href', $('#href').val()).hide();
        }
    });
}

function setFormValues()
{
    var inst = tinyMCEPopup.editor;
    var elm = inst.selection.getNode();

    setHrefFormValue();
    setFormValue('title', inst.dom.getAttrib(elm, 'title'));
    setFormValue('class', inst.dom.getAttrib(elm, 'class'));

    if(inst.dom.getAttrib(elm, 'target') == '_blank')
    {
        $('#openNewWindow').attr('checked', 'checked');
    }
}

function setHrefFormValue()
{
    var inst = tinyMCEPopup.editor;
    var elm = inst.selection.getNode();
    var href = inst.dom.getAttrib(elm, 'href');

    if(/^\{{targetUrl/g.test(href))
    {
        var target = /target=([a-zA-Z0-9]*)/g.exec(href)[1];
        var lang = /lang=([a-zA-Z]*)/g.exec(href)[1];
        var parentId = /parentId=([0-9]*)/g.exec(href)[1];
        $('#target option[value='+target+'_'+lang+'_'+parentId+']').attr('selected', 'selected');
    }
    else if(/^\{{pageUrl/g.test(href))
    {
        var pageId = /docId=([0-9]*)/g.exec(href)[1];
        var pageLang = /lang=([a-zA-Z]*)/g.exec(href)[1];
        $('#page option[value='+pageId+'_'+pageLang+']').attr('selected', 'selected');
    }
    else if(/^\{{mediaUrl/g.test(href))
    {
        var mediaId = /docId=([0-9]*)/g.exec(href)[1];
        $('#media option[value='+mediaId+']').attr('selected', 'selected');
    }
    else
    {
        $('#href').val(href);
    }
}

function setFormValue(name, value) {
	document.forms[0].elements[name].value = value;
}

function isValidMail(mail)
{
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(mail);
}

function checkPrefix(n) {
	if (n.value && isValidMail(n.value) && !/^\s*mailto:/i.test(n.value) && confirm("L'adresse est un e-mail, ajouter le préfixe mailto ?"))
		n.value = 'mailto:' + n.value;

	if (/^\s*www./i.test(n.value) && confirm("L'adresse saisie pointe vers un site externe, ajouter le préfixe http:// ?"))
		n.value = 'http://' + n.value;
}

function setAllAttribs(elm)
{
	var formObj = document.forms[0];

	setAttrib(elm, 'href', setHref());
	setAttrib(elm, 'class', formObj.class.value);
	setAttrib(elm, 'title', formObj.title.value);

    if($('#openNewWindow').attr('checked'))
    {
        setAttrib(elm, 'target', '_blank');
    }
    else
    {
        setAttrib(elm, 'target', '');
    }
}

function setHref()
{
    if($('#href').val() != '' && $('#href').attr('disabled') != 'disabled')
    {
        return $('#href').val();
    }
    if($('#page option:selected').val() != 'null' && $('#page').attr('disabled') != 'disabled')
    {
        val = $('#page option:selected').val().split('_');
        return '{{pageUrl docId='+val[0]+' lang='+val[1]+'}}';
    }
    if($('#target option:selected').val() != 'null' && $('#target').attr('disabled') != 'disabled')
    {
        val = $('#target option:selected').val().split('_');
        return '{{targetUrl target='+val[0]+' lang='+val[1]+' parentId='+val[2]+'}}';
    }
    if($('#media option:selected').val() != 'null' && $('#media').attr('disabled') != 'disabled')
    {
        return '{{mediaUrl docId='+$('#media option:selected').val()+'}}';
    }
}

function hasHref()
{
    if($('#href').val() != '' && $('#href').attr('disabled') != 'disabled')
    {
        return true;
    }
    if($('#page option:selected').val() != 'null' && $('#page').attr('disabled') != 'disabled')
    {
        return true;
    }
    if($('#target option:selected').val() != 'null' && $('#target').attr('disabled') != 'disabled')
    {
        return true;
    }
    if($('#media option:selected').val() != 'null' && $('#media').attr('disabled') != 'disabled')
    {
        return true;
    }
    return false;
}

function setAttrib(elm, attrib, value)
{
	var formObj = document.forms[0];
	var valueElm = formObj.elements[attrib.toLowerCase()];
	var dom = tinyMCEPopup.editor.dom;

	if (typeof(value) == "undefined" || value == null) {
		value = "";

		if (valueElm)
			value = valueElm.value;
	}

	// Clean up the style
	if (attrib == 'style')
		value = dom.serializeStyle(dom.parseStyle(value));

	dom.setAttrib(elm, attrib, value);
}

function insertAction() {
	var inst = tinyMCEPopup.editor;
	var elm, elementArray, i;

	elm = inst.selection.getNode();

    if($('#href').val() != '' && $('#href').attr('disabled') != 'disabled')
    {
        checkPrefix(document.forms[0].href);
    }

	elm = inst.dom.getParent(elm, "A");

	// Remove element if there is no href
	if (!hasHref()) {
		tinyMCEPopup.execCommand("mceBeginUndoLevel");
		i = inst.selection.getBookmark();
		inst.dom.remove(elm, 1);
		inst.selection.moveToBookmark(i);
		tinyMCEPopup.execCommand("mceEndUndoLevel");
		tinyMCEPopup.close();
		return;
	}

	tinyMCEPopup.execCommand("mceBeginUndoLevel");

	// Create new anchor elements
	if (elm == null) {
		tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1});

		elementArray = tinymce.grep(inst.dom.select("a"), function(n) {return inst.dom.getAttrib(n, 'href') == '#mce_temp_url#';});
		for (i=0; i<elementArray.length; i++)
			setAllAttribs(elm = elementArray[i]);
	} else
		setAllAttribs(elm);

	// Don't move caret if selection was image
	if (elm.childNodes.length != 1 || elm.firstChild.nodeName != 'IMG') {
		inst.focus();
		inst.selection.select(elm);
		inst.selection.collapse(0);
		tinyMCEPopup.storeSelection();
	}

	tinyMCEPopup.execCommand("mceEndUndoLevel");
	tinyMCEPopup.close();
}

$(document).ready(function(){
    initLinkManager();
    linkLimiter();
});